package gson;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/***
 * gson typeAdapter
 */
public class NumberTypeAdapters {

	public static final DoubleTypeAdatper  DOUBLE_TYPE_ADATPER  = new DoubleTypeAdatper();
	public static final FloatTypeAdatper   FLOAT_TYPE_ADATPER   = new FloatTypeAdatper();
	public static final LongTypeAdapter    LONG_TYPE_ADAPTER    = new LongTypeAdapter();
	public static final IntegerTypeAdapter INTEGER_TYPE_ADAPTER = new IntegerTypeAdapter();

	private static class DoubleTypeAdatper extends NumberTypeAdapter<Double> {

		@Override
		protected Double parse(String str) {
			return Double.valueOf(str);
		}
	}

	private static class FloatTypeAdatper extends NumberTypeAdapter<Float> {

		@Override
		protected Float parse(String str) {
			return Float.valueOf(str);
		}
	}

	private static class LongTypeAdapter extends NumberTypeAdapter<Long> {

		@Override
		protected Long parse(String str) {
			return Long.valueOf(str);
		}
	}

	private static class IntegerTypeAdapter extends NumberTypeAdapter<Integer> {

		@Override
		protected Integer parse(String str) {
			return Integer.valueOf(str);
		}
	}

	private static abstract class NumberTypeAdapter<T extends Number> extends TypeAdapter<T> {
		@Override
		public void write(JsonWriter out, Number value) throws IOException {
			// out.value(value); // 这个方法没回调
		}

		@Override
		public T read(JsonReader in) throws IOException {
			try {
				String str = in.nextString();

				if (!str.equals("")) {
					return parse(str);
				}
			} catch (Exception e) {}

			return parse("0");
		}

		protected abstract T parse(String str);
	}
}
